package com.erlang.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description：springmvc的void的参数返回
 */
@Controller
@RequestMapping(value = "void-type")
public class VoidTypeController {

    /**
     * @Description 通过request的转发来访问指定页面
     * 范围：项目内使用
     * 请求次数：1次
     * 可以传递值
     */
    @RequestMapping(value = "request-forward")
    public void requestForward(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setAttribute("content", "request-forward");
            request.getRequestDispatcher("/WEB-INF/views/succeed.jsp")
                    .forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 通过response的重定向访问其他路径
     * 范围：项目内重定向、可以访问其他项目
     * 请求次数：2次
     * 2次请求中无法传递值
     */
    @RequestMapping(value = "response-redirect")
    public void responseRedirect(HttpServletRequest request,HttpServletResponse response){
        try {
            //response.sendRedirect("request-forward");
            response.sendRedirect("http://www.baidu.com");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 直接输出字符串在页面
     */
    @RequestMapping(value = "response-return")
    public void responseReturn(HttpServletResponse response){
        response.setContentType("application/json;charset =utf-8");
        String flag = "{\"id\":1,\"name\":\"小明\"}";
        try {
            response.getWriter().write(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}